package com.universal.frame.generalutils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/*
 * Author: wangjie Email:wangj@bluemobi.sh.cn
 * Created Date:2014-10-22
 * Copyright @ 2014 BU
 * Description: 类描述
 *	MD5加密
 * History:
 */
public class Md5Encryp {

    /**
     * TODO(这里用一句话描述这个方法的作用) 对字符串进行md5加密，把字符串转化为32位小写加密字符串
     *
     * @param plainText
     * @return String
     * @author wangj@bluemobi.sh.cn 2014-10-22 下午3:48:39
     */
    public static String encryption(String plainText) {
        String re_md5 = new String();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();

            int i;

            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }

            re_md5 = buf.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return re_md5;
    }

    public static String encode(String password) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] result = digest.digest(password.getBytes());
            StringBuffer sb = new StringBuffer();
            for (byte b : result) {
                int number = (int) (b & 0xff);
                String str = Integer.toHexString(number);
                if (str.length() == 1) {
                    sb.append("0");
                }
                sb.append(str);
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();

            return "";
        }
    }

}
